package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

//    minio:
//    endpointUrl: http://192.168.6.102:9000
//    accessKey: admin
//    secreKey: admin123456
//    bucketName: gmall
    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secreKey}")
    private String secreKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    // /admin/product/fileUpload
    // 文件上传，这里使用的是往minio服务器存储
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{

        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpointUrl)
                        .credentials(accessKey, secreKey)
                        .build();

        // Make 'asiatrip' bucket if not exist.
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            // Make a new bucket called 'asiatrip'.
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } else {
            System.out.println("Bucket 'asiatrip' already exists.");
        }

        // 截取文件名中的文件类型  png
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String filename = System.currentTimeMillis() + UUID.randomUUID().toString() + "." + extension;

        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
                        file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());

        String url = endpointUrl + "/" + bucketName + "/" + filename;

        return Result.ok(url);
    }
}
